/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2019年1月7日
 */

package com.massyframework.beanskin.util.threadlocal;

/**
 * {@link BindableRunnable}, 支持线程变量绑定的Runnable
 */
public abstract class BindableRunnable implements Runnable {

    private ThreadLocalBinder binder;

    /**
     * 构造方法
     */
    public BindableRunnable(){

    }

    /**
     * 构造方法
     * @param binder {@link ThreadLocalBinder}
     */
    public BindableRunnable(ThreadLocalBinder binder){
        this.binder = binder;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public final void run() {
        ThreadLocalBinder binder = this.getThreadLocalBinder();
        if (binder != null){
            binder.bind();
        }
        this.doRun();
    }

    /**
     * 线程变量绑定器
     * @return {@link ThreadLocalBinder}
     */
    public ThreadLocalBinder getThreadLocalBinder(){
        return this.binder;
    }
    /**
     * 设置{@link ThreadLocalBinder}实例
     * @param binder {@link ThreadLocalBinder}
     */
    public void setThreadLocalBinder(ThreadLocalBinder binder){
        this.binder = binder;
    }

    protected abstract void doRun();
}
